﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace ExtendBLL
{
    public class FavoriteResource : LabMS.BLL.FavoriteResource
    {
        public int Insert(LabMS.Model.FavoriteResource model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("if exists(select null from FavoriteResource where UserID=@UserID and ResourceID=@ResourceID and UserType=@UserType) return; else begin ");
            strSql.Append("insert into FavoriteResource(");
            strSql.Append("UserID,ResourceID,UserType)");
            strSql.Append(" values (");
            strSql.Append("@UserID,@ResourceID,@UserType)");
            strSql.Append(";select @@IDENTITY; end");
            SqlParameter[] parameters = {
					new SqlParameter("@UserID", SqlDbType.Int,4),
					new SqlParameter("@ResourceID", SqlDbType.Int,4),
					new SqlParameter("@UserType", SqlDbType.Int,4)};
            parameters[0].Value = model.UserID;
            parameters[1].Value = model.ResourceID;
            parameters[2].Value = model.UserType;

            object obj = Maticsoft.DBUtility.DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }

        public void Delete(LabMS.Model.FavoriteResource model)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("delete from FavoriteResource where UserID=@UserID and ResourceID=@ResourceID and UserType=@UserType ");
            SqlParameter[] parameters = {
					new SqlParameter("@UserID", SqlDbType.Int,4),
					new SqlParameter("@ResourceID", SqlDbType.Int,4),
					new SqlParameter("@UserType", SqlDbType.Int,4)};
            parameters[0].Value = model.UserID;
            parameters[1].Value = model.ResourceID;
            parameters[2].Value = model.UserType;

            Maticsoft.DBUtility.DbHelperSQL.ExecuteSql(sb.ToString(), parameters);
        }

        public DataSet GetFavorites(int userID, int userType)
        {
            Resource resource = new Resource();
            DataSet ds = resource.GetList(" [ID] in (select distinct ResourceID from FavoriteResource where UserID=" + userID + " and UserType=" + userType + ")");

            return ds;
        }
    }
}
